//
//  UIDevice+FWPowerful.m
//  iOSToolkit
//
//  Created by Evan Xie on 9/17/14.
//  Copyright (c) 2014 Family Wings. All rights reserved.
//

#include <sys/sysctl.h>

#import "UIDevice+FWPowerful.h"


@implementation UIDevice (FWPowerful)

- (NSUInteger)cpuFrequency
{
    return [self getSystemInformation:HW_CPU_FREQ];
}

- (NSUInteger)busFrequency
{
    return [self getSystemInformation:HW_BUS_FREQ];
}

- (NSUInteger)totalMemory
{
    return [self getSystemInformation:HW_PHYSMEM];
}

- (NSUInteger)userMemory
{
    return [self getSystemInformation:HW_USERMEM];
}

- (NSUInteger)maxSocketBufferSize
{
    return [self getSystemInformation:KIPC_MAXSOCKBUF];
}

- (unsigned long long)totalDiskSpace
{
    NSDictionary *fsAttributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
    return [fsAttributes[NSFileSystemSize] unsignedLongLongValue];
}

- (unsigned long long)freeDiskSpace
{
    NSDictionary *fsAttributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
    return [fsAttributes[NSFileSystemFreeSize] unsignedLongLongValue];
}



- (NSString *)platformCode
{
    return [self getSystemInformationByName:"hw.machine"];
}


// Thanks, Tom Harrington (Atomicbird)
- (NSString *)hardwareModel
{
    return [self getSystemInformationByName:"hw.model"];
}


#pragma mark - Private Methods

- (NSUInteger)getSystemInformation: (uint) typeSpecifier
{
    size_t size = sizeof(int);
    int results;
    int mib[2] = {CTL_HW, typeSpecifier};
    sysctl(mib, 2, &results, &size, NULL, 0);
    return (NSUInteger) results;
}

- (NSString *)getSystemInformationByName:(char *)typeSpecifier
{
    size_t size;
    sysctlbyname(typeSpecifier, NULL, &size, NULL, 0);
    
    char *answer = malloc(size);
    sysctlbyname(typeSpecifier, answer, &size, NULL, 0);
    
    NSString *results = [NSString stringWithCString:answer encoding: NSUTF8StringEncoding];
    
    free(answer);
    return results;
}

@end
